import React, { Component } from 'react';
import { TextInput, TouchableOpacity, View, ImageBackground } from 'react-native';
import { connect } from 'react-redux';
import { Toast, Flex } from 'antd-mobile-rn';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/icomoon';
import CText from '../../components/CText';
import { colors } from '../../styles/basic';
import { createStyles } from '../../utils/view';
import toolsVerifi from '../../utils/verifi';
import authActions from '../../controllers/auth/actions';
import Scene from '../screen/scene';
import { getCode } from '../../service/user/index';

class Login extends Component {

  static navigatorStyle = {
    navBarHidden: true,
    navBarNoBorder: true,
    drawUnderNavBar: true,
    drawUnderTabBar: true,
  }

  constructor(props) {
    super(props);
    // this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
    this.inputRefs = [];
    this.pageIndex = 1;
    this.startTime = 0;
    this.state = {
      nick_name: 'test',
      wechat: 'testchat',
      mobile: '18874130125',
      ucode: '123456',               // 登录的code
      codeText: '发送验证码',
    };
  }

  componentWillUnmount() {
    clearInterval(this.timeInter);
  }
  /**
   * 发送获取验证码
   */
  onSendCode = () => {
    // 60秒后重新获取

    this.onblur();

    let mobile = this.state.mobile;
    mobile = mobile.replace(/ /g, '');
    if (!toolsVerifi.isPhone(mobile)) {
      return Toast.fail('请输入正确的手机号码');
    }

    if (this.startTime === 0) {
      this.startTime = 60;

      this.timeInter = setInterval(() => {
        if (this.startTime > 0) {
          this.setState({ codeText: `${this.startTime}秒后重新获取` });
          this.startTime--;
        } else {
          this.setState({ codeText: `发送验证码` });
          clearInterval(this.timeInter);
        }
      }, 1000);

      // 发送登录验证码
      getCode(mobile).then((data) => {
        console.log('getCode', data);
        if (data.code !== 0) {
          Toast.fail(data.msg);
        }
      }).catch(() => { });
    }
  }
  /**
   * 失去焦点， 收起输入框
   */
  onblur = () => {
    this.inputRefs.map((obj) => {
      try {
        obj && obj.blur && obj.blur();
      } catch (e) {
      }
    });
  }
  /**
   * 提交注册
   */
  onSend() {
    console.log('onSend');
    this.onblur();

    let { nick_name, ucode, mobile, wechat } = this.state;

    mobile = mobile.replace(/ /g, '');

    if (!toolsVerifi.isPhone(mobile)) {
      return Toast.fail('请输入正确的手机号码');
    }
    this.props.Login({ mobile, wechat, nick_name, code: ucode });

  }

  render() {
    const { loading } = this.props;
    return <Scene style={styles.wrapper} isLoading={loading} >
      <LinearGradient style={styles.head} colors={['#F8F1A1', '#FCE56B', '#C9A43C']} start={{ x: 0, y: 0.5 }} end={{ x: 1, y: 0.5 }} >
        <View style={styles.logo}></View>
      </LinearGradient>
      <Flex style={styles.login_box} direction="column" justify="start" align="center">
        {/* 昵称 */}
        <Flex style={styles.login_item}>
          <Icon style={styles.login_icon} name="name_h" />
          <TextInput
            ref={(r) => { this.inputRefs.push(r) }}
            style={styles.login_input}
            value={this.state.nick_name}
            keyboardType="default"
            placeholder="昵称"
            onChange={(event) => {
              event.nativeEvent.text = event.nativeEvent.text.replace(/ /g, '').replace(/[^\d]/g, '');
              this.setState({
                nick_name: event.nativeEvent.text,
              });
            }}
            underlineColorAndroid={'transparent'}
          />
        </Flex>
        {/* 微信号 */}
        <Flex style={styles.login_item}>
          <Icon style={styles.login_icon} name="name_h" />
          <TextInput
            ref={(r) => { this.inputRefs.push(r) }}
            style={styles.login_input}
            value={this.state.wechat}
            keyboardType="default"
            placeholder="微信号"
            onChange={(event) => {
              event.nativeEvent.text = event.nativeEvent.text.replace(/ /g, '').replace(/[^\d]/g, '');
              this.setState({
                wechat: event.nativeEvent.text,
              });
            }}
            underlineColorAndroid={'transparent'}
          />
        </Flex>
        {/* 手机号 */}
        <Flex style={styles.login_item}>
          <Icon style={styles.login_icon} name="name_h" />
          <TextInput
            ref={(r) => { this.inputRefs.push(r) }}
            style={styles.login_input}
            value={this.state.mobile}
            keyboardType="numeric"
            maxLength={13}
            placeholder="请输入手机号"
            onChange={(event) => {
              event.nativeEvent.text = event.nativeEvent.text.replace(/ /g, '').replace(/[^\d]/g, '');
              if (event.nativeEvent.text !== this.state.mobile.replace(/ /g, '')) {
                event.nativeEvent.text = event.nativeEvent.text.replace(/(^\d{3}|\d{4}\B)/g, '$1 ');
              }
              this.setState({
                mobile: event.nativeEvent.text,
              });
            }}
            underlineColorAndroid={'transparent'}
          />
        </Flex>
        <Flex style={styles.login_code_item}>
          <TextInput
            ref={(r) => { this.inputRefs.push(r) }}
            style={styles.login_code_input}
            value={this.state.ucode}
            keyboardType="numeric"
            placeholder="验证码"
          />
          <TouchableOpacity style={styles.ucode_button} onPress={this.onSendCode}>
            <CText color="#fff">{this.state.codeText}</CText>
          </TouchableOpacity>
        </Flex>
      </Flex>
      <ImageBackground source={require('../../assets/img/home/btn_buy.png')} resizeMode="stretch" style={styles.login_button}>
        <TouchableOpacity activeOpacity={0.6} onPress={() => { this.onSend() }}>
          <CText>登录</CText>
        </TouchableOpacity>
      </ImageBackground>
    </Scene>;

  }
}

let styles = {
  wrapper: {
    flex: 1,
    backgroundColor: colors.cf2f,
    flexDirection: 'column',
    justifyContent: 'flex-start',
    alignItems: 'center',
  },
  head: {
    height: 614,
    flexDirection: 'column',
    justifyContent: 'flex-start',
    alignItems: 'center',
  },
  logo: {
    width: 200,
    height: 200,
    borderRadius: 32,
    backgroundColor: '#fff',
    marginTop: 149,
  },
  login_box: {
    width: 690,
    height: 534,
    paddingTop: 56,
    backgroundColor: '#fff',
    position: 'absolute',
    top: 399,
    left: 30,
    shadowColor: '#F8F1A1',
    shadowOffset: {
      width: 4,
      height: 4
    },
    shadowOpacity: 1,
    shadowRadius: 10,
    borderRadius: 8,
  },
  login_item: {
    width: 600,
    height: 88,
    borderRadius: 44,
    borderWidth: 1,
    borderColor: '#CCCCCC',
    paddingLeft: 44,
    marginBottom: 30,
  },
  login_icon: {
    fontSize: 44,
    color: '#ccc',
    marginRight: 21,
  },
  login_input: {
    flex: 1,
    fontSize: 30,
  },
  login_code_item: {
    width: 600,
    height: 88,
    borderRadius: 44,
    borderWidth: 1,
    borderColor: '#CCCCCC',
    marginBottom: 30,
    overflow: 'hidden',
  },
  login_code_input: {
    flex: 1,
    fontSize: 30,
    textAlign: 'center',
  },
  ucode_button: {
    flex: 1,
    height: 88,
    borderTopRightRadius: 44,
    borderBottomRightRadius: 44,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#C9A43C'
  },
  login_button: {
    marginTop: 383,
    width: 600,
    height: 88,
    borderRadius: 44,
    marginLeft: 75,
    justifyContent: 'center',
    alignItems: 'center',
  },
};

styles = createStyles(styles);

export default connect((Store) => {
  return { loading: Store.AuthRenderData.loading };
}, { Login: authActions.Login })(Login);
